<script setup lang="ts">
import { reactive, ref } from "vue";
import { UseUserStore } from "@/store/modules/index.ts";
import { useRouter, useRoute } from "vue-router";
import { reqLogin } from "@/api/user/index";
import { ElNotification } from "element-plus";

// 路由
let $route = useRoute();
let $router = useRouter();
// 状态存储仓库
let userStore = UseUserStore();

let loginForm = reactive({
  username: "admin",
  password: "123456",
});

let loading = ref(false);

const login = () => {
  if (loading.value) return;
  loading.value = true;
  reqLogin(loginForm)
    .then((res) => {
      loading.value = false;
      ElNotification({
        title: "登录成功",
        type: "success",
      });
      userStore.saveToken(res.data.token);
      let redirect: any = $route.query.redirect;
      $router.replace(redirect || "/");
    })
    .catch((err) => {
      loading.value = false;
      ElNotification({
        title: "登录失败",
        type: "error",
      });
      console.log(err.message);
    });
};
</script>

<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-card class="login_form">
          <h1>Vue-Admin</h1>
          <el-form :model="loginForm" ref="loginForms">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                clearable
                placeholder="Username"
                size="large"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                show-password
                v-model="loginForm.password"
                size="large"
                placeholder="Password"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              size="default"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped></style>
